<template>
    <div class="login-form">
        <el-input
            v-model="accountLoginForm.username"
            placeholder="请输入你的账号"
            @keyup.enter="login"
        />
        <el-input
            v-model="accountLoginForm.password"
            :type="passwordShow ? 'text' : 'password'"
            class="password-input"
            placeholder="请输入登录密码"
            @keyup.enter="login"
        >
            <template #suffix>
                <img class="password-input-icon" :src="passwordInputIcon" @click="showOrHidePassword" />
            </template>
        </el-input>
        <el-button
            class="btn"
            :disabled="!accountLoginForm.username || !accountLoginForm.password"
            @click="login"
        >
            <span>登录</span>
        </el-button>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, defineExpose } from 'vue';
import { useStore } from 'vuex';
import { getAESInfo, encrypt } from '@/utils/crypto/encryption';
import { AccountLoginForm } from '../loginType';
import useLocalLogin from '../hooks/useLocalLogin';
import * as authApi from '@/api/auth';
import XCMessageMgr from '@/utils/XCMessageMgr';
const store = useStore();

const accountLoginForm = reactive<AccountLoginForm>({
    username: '',
    password: '',
});
const passwordShow = ref(false);
let passwordInputIcon = ref(new URL('../../../assets/login/icon-password-hide.png', import.meta.url).href);

const showOrHidePassword = async () => {
    passwordShow.value = !passwordShow.value;
    if (passwordShow.value) {
        passwordInputIcon.value = new URL('../../../assets/login/icon-password-show.png', import.meta.url).href;
    } else {
        passwordInputIcon.value = new URL('../../../assets/login/icon-password-hide.png', import.meta.url).href;
    }
};
const loginByUsernameWithEncrypt = async (form = {}, productCode = '') => {
    const key = await getAESInfo();
    const paramsRaw = {
        ...form,
        clientId: key.clientId,
        productCode: productCode,
    };
    const encryptedParams = encrypt(JSON.stringify(paramsRaw), key.AESKey);
    return await authApi.loginWithEncrypt({
        encryptInfo: {
            clientId: key.clientId,
            encryptInfo: encryptedParams,
        }
    });
};
// 登录
const login = async () => {
    if (!accountLoginForm.username || !accountLoginForm.password) {
        return;
    }
    store.commit('app/setLoginLoading', true);
    const productCode = window.XCConfig.VITE_PRODUCT_CODE || '';
    let res;
    // 用户名密码登录 参数加密
    try {
        res = await loginByUsernameWithEncrypt(accountLoginForm, productCode);
        store.commit('app/setLoginLoading', false);
        if(!res.accessToken) {
            XCMessageMgr.Instance.showConfirm(res.msg);
        }
        else {
            console.log('res',res);
            useLocalLogin(res);
        }
    } catch (e) {
        store.commit('app/setLoginLoading', false);
        // 加密登录失败，自动尝试非加密方式
        // 用户名密码错误，不重试
        if (e.code === '081') {
            return;
        }
        // 帐号被锁定 不重试
        if (e.code === '001') {
            return;
        }
        store.commit('app/setLoginLoading', true);
        try {
            res = await authApi.login({...accountLoginForm, productCode});
            useLocalLogin(res);
        } catch(e) {
            store.commit('app/setLoginLoading', false);
            console.error(e);
        }
    }
};

onMounted(() => {});

// 对外暴露可执行方法
defineExpose({});
</script>

<style lang="scss" scoped>
.login-form {
    position: relative;
    .password-input {
        ::v-deep .el-input__inner {
            padding-right: 50px;
        }
    }
    .password-input-icon {
        width: 20px;
        height: 20px;
        cursor: pointer;
    }
    .btn {
        width: 100%;
        margin-top: 34px;
        font-size: 14px;
        font-family: PingFang SC-Regular, PingFang SC;
        font-weight: 400;
        background: #e60044;
        color: #fff;
        border: none;
        height: 40px;
        &.is-disabled {
            background: #f380a1;
        }
    }
}
::v-deep {
    .el-input {
        & + .el-input {
            margin-top: 20px;
        }
    }
    .el-input__inner {
        height: 36px !important;
        line-height: 36px;
    }
    .el-input__suffix {
        display: flex;
        align-items: center;
    }
}
</style>
